"use client"

import { useState } from "react"
import { Copy, Check } from "lucide-react"
import { Button } from "@/components/ui/button"

type LayoutCodeProps = {
  xml: string
}

export function LayoutCode({ xml }: LayoutCodeProps) {
  const [copied, setCopied] = useState(false)

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(xml)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error("Failed to copy text: ", err)
    }
  }

  return (
    <div className="relative">
      <pre className="p-4 bg-gray-100 rounded-md overflow-auto text-sm max-h-[500px]">
        <code>{xml}</code>
      </pre>
      <Button size="sm" variant="ghost" className="absolute top-2 right-2" onClick={copyToClipboard}>
        {copied ? (
          <>
            <Check className="h-4 w-4 mr-1" />
            已复制
          </>
        ) : (
          <>
            <Copy className="h-4 w-4 mr-1" />
            复制
          </>
        )}
      </Button>
    </div>
  )
}
